package com.example.springboot_shiro.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springboot_shiro.annotation.LoginToken;
import com.example.springboot_shiro.annotation.PassToken;
import com.example.springboot_shiro.domain.test.User;
import com.example.springboot_shiro.service.UserService;
import com.example.springboot_shiro.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author: lqy
 * @date: 2021/9/8 14:40
 * @description:
 */
@Api(tags = "test")
@Controller
@AllArgsConstructor
@RequestMapping("/login")
public class UserController {
    private final UserService userService;

    @RequestMapping("/error")
    @ResponseBody
    public JSONObject error() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "您没有访问权限");
        jsonObject.put("code", "401");
        return jsonObject;
    }

    @PostMapping("/login")
    @PassToken
    @ApiOperation(value = "login")
    @ResponseBody
    public Object login(String userName, String password) {
        JSONObject jsonObject = new JSONObject();
        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(userName, password));
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return "用户名错误";
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return "密码错误";
        }
        String token = JwtUtils.sign(userName);
        jsonObject.put("token", token);
        return jsonObject;

    }


    @ApiOperation(value = "register")
    @PostMapping("/register")
    @ResponseBody
    public String register(User user) {
        int update = 0;
        try {
            update = userService.register(user);
        } catch (Exception e) {
            e.printStackTrace();

        }
        if (update > 0) {
            return "注册成功";
        }
        return "注册失败";
    }

    @ApiOperation(value = "测试token")
    @PostMapping("/getToken")
    @ResponseBody
    @LoginToken
    @RequiresRoles("user")
    public String getToekn() {

        return "测试token";
    }

    @ApiOperation(value = "测试角色")
    @PostMapping("/getRole")
    @ResponseBody
    @LoginToken
    public String getRole() {

        return "测试Role";
    }


}
